package com.evenmo.poi;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * This is Description excel样式及合并单元格测试
 *
 * @author moyongjun
 * @date 2019/12/02
 */
public class ExcelStyleDemo {

    public void testExcelStyle(){

        //创建工作薄
        HSSFWorkbook workbook=new HSSFWorkbook();
        //创建合并单元格对象
        CellRangeAddress cellRangeAddress= new CellRangeAddress(2, 2, 2, 4);


        //创建单元格样式
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        //设置对齐方式
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//居中对齐
        cellStyle.setAlignment(HSSFCellStyle.VERTICAL_BOTTOM);

        //设置背景色
        //设置填充模式
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cellStyle.setFillBackgroundColor(HSSFColor.YELLOW.index);
        cellStyle.setFillBackgroundColor(HSSFColor.GREEN.index);

        //创建字体
        HSSFFont font = workbook.createFont();
        //设置字体
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setFontHeightInPoints((short) 16);
        font.setColor(HSSFFont.COLOR_RED);

        //将字体加入到样式中
        cellStyle.setFont(font);




        //创建工作表
        HSSFSheet sheet = workbook.createSheet();

        //将合并单元格对象加入到工作表中
        sheet.addMergedRegion(cellRangeAddress);



        //创建行
        HSSFRow row = sheet.createRow(2);

        //创建单元格
        HSSFCell cell = row.createCell(2);

        cell.setCellValue("Hello World! this is my excel test！");


        //单元格添加样式
        cell.setCellStyle(cellStyle);


        String fileName="HelloWorld.xls";

        FileOutputStream fos= null;
        try {
            fos = new FileOutputStream(fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            workbook.write(fos);
            System.out.println("导出完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
